<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { addDataApi, updateDataApi } from '@/service/api';

defineOptions({
  name: 'DataApiOperateDrawer'
});

interface Props {
  operateType: 'add' | 'edit';
  rowData?: any;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', { required: true });

const title = computed(() => (props.operateType === 'add' ? '新增数据API' : '编辑数据API'));

const formRef = ref<HTMLElement & FormInst>();

const formModel = reactive({
  id: undefined as number | undefined,
  name: '',
  path: '',
  method: 'GET',
  sqlTemplate: '',
  requestParams: '',
  responseFields: '',
  authType: 'TOKEN',
  status: 'DRAFT',
  version: '1.0',
  rateLimit: 100,
  desensitizeRules: '',
  description: '',
  projectId: undefined as number | undefined,
  remark: ''
});

const rules: FormRules = {
  name: [{ required: true, message: '请输入API名称', trigger: 'blur' }],
  path: [
    { required: true, message: '请输入API路径', trigger: 'blur' },
    { pattern: /^\/[\w/-]*$/, message: 'API路径格式不正确，应以/开头', trigger: 'blur' }
  ],
  method: [{ required: true, message: '请选择请求方法', trigger: 'change' }],
  sqlTemplate: [{ required: true, message: '请输入SQL模板', trigger: 'blur' }]
};

const methodOptions = [
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' }
];

const authTypeOptions = [
  { label: 'TOKEN', value: 'TOKEN' },
  { label: 'API_KEY', value: 'API_KEY' },
  { label: 'OAUTH', value: 'OAUTH' }
];

const statusOptions = [
  { label: '草稿', value: 'DRAFT' },
  { label: '已发布', value: 'PUBLISHED' },
  { label: '已下线', value: 'OFFLINE' }
];

watch(visible, () => {
  if (visible.value) {
    if (props.operateType === 'edit' && props.rowData) {
      Object.assign(formModel, props.rowData);
    } else {
      handleReset();
    }
  }
});

function handleReset() {
  formRef.value?.restoreValidation();
  Object.assign(formModel, {
    id: undefined,
    name: '',
    path: '',
    method: 'GET',
    sqlTemplate: '',
    requestParams: '',
    responseFields: '',
    authType: 'TOKEN',
    status: 'DRAFT',
    version: '1.0',
    rateLimit: 100,
    desensitizeRules: '',
    description: '',
    projectId: undefined,
    remark: ''
  });
}

async function handleSubmit() {
  await formRef.value?.validate();
  try {
    if (props.operateType === 'add') {
      await addDataApi(formModel);
      window.$message?.success('新增成功');
    } else {
      await updateDataApi(formModel);
      window.$message?.success('更新成功');
    }
    visible.value = false;
    emit('success');
  } catch (error) {
    console.error('操作失败:', error);
  }
}

function handleClose() {
  visible.value = false;
}
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" :width="720">
    <NDrawerContent closable>
      <NForm ref="formRef" :model="formModel" :rules="rules" label-placement="left" :label-width="120">
        <NGrid :cols="24" :x-gap="18">
          <NFormItemGridItem :span="24" label="API名称" path="name">
            <NInput v-model:value="formModel.name" placeholder="请输入API名称" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="API路径" path="path">
            <NInput v-model:value="formModel.path" placeholder="/api/data/query" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="版本号" path="version">
            <NInput v-model:value="formModel.version" placeholder="1.0" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="请求方法" path="method">
            <NSelect v-model:value="formModel.method" :options="methodOptions" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="鉴权类型" path="authType">
            <NSelect v-model:value="formModel.authType" :options="authTypeOptions" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="状态" path="status">
            <NSelect v-model:value="formModel.status" :options="statusOptions" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="12" label="限流(次/秒)" path="rateLimit">
            <NInputNumber v-model:value="formModel.rateLimit" :min="1" :max="10000" style="width: 100%" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="SQL模板" path="sqlTemplate">
            <NInput
              v-model:value="formModel.sqlTemplate"
              type="textarea"
              placeholder="SELECT * FROM table WHERE id = #{id}"
              :rows="6"
            />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="请求参数" path="requestParams">
            <NInput
              v-model:value="formModel.requestParams"
              type="textarea"
              placeholder='[{"name":"id","type":"number","required":true}]'
              :rows="4"
            />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="返回字段" path="responseFields">
            <NInput
              v-model:value="formModel.responseFields"
              type="textarea"
              placeholder='[{"name":"id","type":"number"},{"name":"name","type":"string"}]'
              :rows="4"
            />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="脱敏规则" path="desensitizeRules">
            <NInput
              v-model:value="formModel.desensitizeRules"
              type="textarea"
              placeholder='{"phone":"mobile","idCard":"idCard"}'
              :rows="3"
            />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="API描述" path="description">
            <NInput v-model:value="formModel.description" type="textarea" placeholder="请输入API描述" :rows="3" />
          </NFormItemGridItem>

          <NFormItemGridItem :span="24" label="备注" path="remark">
            <NInput v-model:value="formModel.remark" type="textarea" placeholder="请输入备注" :rows="2" />
          </NFormItemGridItem>
        </NGrid>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleClose">取消</NButton>
          <NButton type="primary" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
